package com.company.cloud.company.modules.mgr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.company.modules.base.entity.CustomerRewardConfigInfo;
import com.company.cloud.company.modules.base.service.CustomerRewardConfigInfoService;
import com.company.cloud.company.modules.cache.utils.CompanyConvertUtils;
import com.company.cloud.company.modules.mgr.controller.req.CustomerRewardQueryPageParam;
import com.company.cloud.company.modules.mgr.controller.req.CustomerRewardSaveParam;
import com.company.cloud.company.modules.api.response.CustomerRewardResp;
import com.company.cloud.company.modules.mgr.service.CustomerRewardMgrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerRewardMgrServiceImpl implements CustomerRewardMgrService {

    @Autowired
    private CustomerRewardConfigInfoService customerRewardConfigInfoService;

    @Override
    public IPage<CustomerRewardResp> query(CustomerRewardQueryPageParam params, String companyNo) {
        IPage<CustomerRewardConfigInfo> page = customerRewardConfigInfoService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<CustomerRewardConfigInfo>()
                        .eq(CheckUtils.hasText(companyNo), "company_no", companyNo)
                        .eq(CheckUtils.hasBigDecimal(params.getMiniCashFund()), "mini_cash_fund", params.getMiniCashFund())
                        .eq(CheckUtils.hasBigDecimal(params.getTaxCash()), "tax_cash", params.getTaxCash())
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
        );
        return page.convert(CompanyConvertUtils::getCustomerRewardResp);
    }

    @Override
    public void saveOrEdit(CustomerRewardSaveParam params, String companyNo, LoginSimpleUserInfo userInfo) {
        CustomerRewardConfigInfo entity = CompanyConvertUtils.getCustomerRewardConfigInfo(params, userInfo.getCompanyNo());
        CustomerRewardConfigInfo old = customerRewardConfigInfoService.getById(userInfo.getCompanyNo());
        if (old == null) {
            entity.addCreateParam(userInfo);
            entity.addEditParam(userInfo);
            customerRewardConfigInfoService.save(entity);
        } else {
            entity.addEditParam(userInfo);
            customerRewardConfigInfoService.updateById(entity);
        }
    }

    @Override
    public CustomerRewardResp get(String companyNo) {
        CustomerRewardConfigInfo entity = customerRewardConfigInfoService.getById(companyNo);
        return CompanyConvertUtils.getCustomerRewardResp(entity);
    }
}
